package hyy_2022;


/**
 * 反转字符串
 * s = "Let's take LeetCode contest"
 * "s'teL ekat edoCteeL tsetnoc"
 *
 * 给定字符串s,反转字符串中每个单词的字符顺序,同时扔保留空格和单词的初始顺序
 */
public class _0821_557_ReverseWords {

    /**
     * 1、将字符串按空格分割为字符串数组
     * 2、遍历数组,将数组中每个单词进行反转
     * @param s
     * @return 反转后的字符串
     */
    public String reverseWords(String s) {
        StringBuilder sb = new StringBuilder();
        String[] words = s.split(" ");
        for(String word : words) {
            if(sb.length() == 0) {
                sb.append(reverseString(word));
            } else {
                sb.append(" ").append(reverseString(word));
            }
        }
        return sb.toString();
    }

    /**
     * 双指针法反转字符串
     * @param s 原始字符串
     * @return 反转后字符串
     */
    public String reverseString(String s) {
        char[] chars = s.toCharArray();
        int left = 0;
        int right = s.length() - 1;
        while(left < right) {
            char temp = chars[left];
            chars[left] = chars[right];
            chars[right] = temp;
            ++ left;
            -- right;
        }
        return new String(chars);
    }
}
